import { _decorator, clamp, Color, Component, EventTouch, Node, Rect, Sprite, UITransform, Vec2, Vec3 } from 'cc';
import { Game } from './Game';
import { PixelSprite } from './PixelSprite';
import { ShapeSprite } from './ShapeSprite';
const { ccclass, property } = _decorator;


//触摸灵敏度
const sensitivity = 2.5;

const v3Temp = new Vec3();
const c4Temp = new Color();


@ccclass('ShapeCtr')
export class ShapeCtr extends Component {


    private isDragging = false;

    //坐标系是在左下角
    private tetrisRect: Rect = null;
    private shape: ShapeSprite = null;
    private tetris: PixelSprite = null;
    private dropShadow: Sprite = null;

    private center = new Vec3();
    private originPos: Vec3 = new Vec3();
    private originScale: Vec3 = new Vec3();


    private gridXY = new Vec2();
    private dropXY = new Vec3();
    private touchPos: Vec2 = new Vec2();
    private fixCenter: Vec2 = new Vec2(0, 0);




    protected onLoad(): void {
        this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }

    onDestroy() {
        this.node.off(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.off(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.off(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.off(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }


    start() {

        this.tetris = Game.instance.tetris;
        this.tetrisRect = this.tetris.totalRect;

        this.dropShadow = Game.instance.dropShadow;
        this.dropShadow.enabled = false; //默认关闭不显示

        this.shape = this.node.getComponentInChildren(ShapeSprite);
        let t = this.shape.node.parent.getComponent(UITransform);
        this.center = t.convertToWorldSpaceAR(Vec3.ZERO);
    }


    moveShadow() {

        let shadow = this.dropShadow;
        this.dropShadow.enabled = true;

        let t = shadow.getComponent(UITransform);
        t.width = this.shape.width; //调整区域大小

        //设置阴影位置
        let wpos = this.shape.node.worldPosition;
        t = this.tetris.getComponent(UITransform);
        let p = t.convertToNodeSpaceAR(wpos, v3Temp);
        shadow.node.setPosition(p.x, 0);

        //设置阴影颜色
        let idx = this.shape.color0Idx
        let color = Game.instance.randColors[idx][0];
        if (color) {
            shadow.color = c4Temp.set(color).lerp(Color.WHITE, 0.5);
        }
    }

    /**
     * 计算下放格子坐标
     * @param x 世界坐标x
     * @param y 世界坐标y
     * @returns 下放格子坐标
     */
    calculateDropCoord(x: number, y: number) {

        // 计算 x, y 在 tetris 区域内的格子索引和实际中心坐标
        let w = this.tetris.texWidth;
        let h = this.tetris.texHeight;
        let size = this.tetris.gridSize;
        let tetrisRect = this.tetrisRect;


        // 转为相对 tetrisRect 左下角的坐标
        let relX = x - tetrisRect.x;
        let relY = y - tetrisRect.y;

        // 计算格子索引
        let gridX = Math.floor(relX * 1.0 / size);
        let gridY = Math.floor(relY * 1.0 / size);

        //下放格子，左上角为0,0
        gridX = Math.max(0, Math.min(w - 1, gridX));
        gridY = h - 1 - Math.max(0, Math.min(h - 1, gridY));

        //下放坐标，左下角为0,0
        let posX = tetrisRect.x + gridX * size;
        let posY = tetrisRect.y + gridY * size;

        //计算结果
        this.dropXY.set(posX, posY, 0);
        this.gridXY.set(gridX, gridY);

        // console.log("drop in tetris borad:",  gridX, gridY);

        return this.dropXY;
    }


    private touchStart(event: EventTouch) {
        //开始拖拽
        this.isDragging = true;

        
        //记录原始位置和缩放,用于恢复
        let node = this.shape.node;
        node.getScale(this.originScale);
        node.getPosition(this.originPos);

        //记录初始触摸位置
        this.touchPos.set(event.getUILocation());

        let center = this.center;
        let transfrom = node.getComponent(UITransform);
        transfrom.setAnchorPoint(0, 1);
        node.setScale(1, 1, 1);

        let w = this.shape.width;
        
        //计算面板最顶部位置
        let offy = this.tetrisRect.y + this.tetrisRect.height - center.y;

        //锁定移动左右边缘
        this.touchPos.x = clamp(this.touchPos.x, this.tetrisRect.x, this.tetrisRect.x + this.tetrisRect.width - w);

        node.setPosition(this.touchPos.x - center.x, offy);

    }

    private topMove(event: EventTouch) {


        let delta = event.getUIDelta();
        this.touchPos.x += delta.x * sensitivity;


        let center = this.center;
        let w = this.shape.width;
        let node = this.shape.node;
        let nodePos = node.getPosition();

        //锁定移动左右边缘
        this.touchPos.x = clamp(this.touchPos.x, this.tetrisRect.x, this.tetrisRect.x + this.tetrisRect.width - w);

        node.setPosition(this.touchPos.x - center.x, nodePos.y);


    }


    private touchEnd(event: EventTouch) {
        let node = this.shape.node;
        let transfrom = node.getComponent(UITransform);
        let UIPos = transfrom.convertToWorldSpaceAR(Vec3.ZERO);
        this.calculateDropCoord(UIPos.x, UIPos.y); //计算下放格子坐标

        //下放方块，并判断是否成功
        let dropFlag = Game.instance.drop(this.shape, this.gridXY);

        //恢复原形状位置和缩放数据
        transfrom.setAnchorPoint(0.5, 0.5);
        node.setPosition(this.originPos);
        node.setScale(this.originScale);
        this.dropShadow.enabled = false;
        this.isDragging = false;

        if (dropFlag) {
            //下放成功，生成下一个
            this.shape.nextShape();
        }
    }


    private onTouchStart(event: EventTouch) {
        if (Game.instance.isGameOver) return;
        if (this.isDragging) return;

        this.touchStart(event);
        this.moveShadow();
    }

    private onTouchMove(event: EventTouch) {
        if (!this.isDragging) return;

        this.topMove(event);
        this.moveShadow();
    }

    private onTouchEnd(event: EventTouch) {
        if (!this.isDragging) return;
        this.touchEnd(event);
    }
}


